package com.kingray.openfire.plugin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.kingray.openfire.plugin.vo.GroupUser;

public class SynchroUsers {
	private static String ip = "10.188.199.3"; //10.188.199.3
	public static void main(String[] args) {
		// try {
		// System.out.println(new String("����".getBytes(),"utf-8").length());
		// } catch (UnsupportedEncodingException e) {
		// e.printStackTrace();
		// }//12
//		List list = getDeletedGroupUsers();
//		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
//			Object object = (Object) iterator.next();
//			System.out.println(object);
//		}
		
		synchroUsers();
		
	}
	
	public static void synchroUsers(){
		addUsers();
		updateUsers();
		deleteFiredUsers();
		addGroups();
	}
	
	
	/**
	 * 添加用户
	 * <br>2013-7-18 上午9:53:57
	 */
	public static void addUsers(){
		List<GroupUser> groupUsers = getGroupUsers();
		for (Iterator iterator = groupUsers.iterator(); iterator.hasNext();) {
			GroupUser groupUser = (GroupUser) iterator.next();
			sendRequestBySocket(groupUser);
		}
	}
	
	/**
	 * 更新用户
	 * <br>2013-7-18 上午9:53:57
	 */
	public static void updateUsers(){
		List<GroupUser> groupUsers = getGroupUsers();
		for (Iterator iterator = groupUsers.iterator(); iterator.hasNext();) {
			GroupUser groupUser = (GroupUser) iterator.next();
			sendUpdateRequestBySocket(groupUser);
		}
	}
	
	/**
	 * 更新分组排序
	 * <br>2013-7-18 上午9:53:57
	 */
	public static void addGroups(){
		List<Group> groups = getGroups();
		for (Iterator iterator = groups.iterator(); iterator.hasNext();) {
			Group group = (Group) iterator.next();
			sendGroupRequestBySocket(group);
		}
	}
	
	
	/**
	 * 删除离职用户
	 */
	public static void deleteFiredUsers(){
		List list = getDeletedGroupUsers();
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			GroupUser groupUser = (GroupUser) iterator.next();
			sendDeleteRequestBySocket(groupUser);
		}
		
	}
	
	private static void sendDeleteRequestBySocket(GroupUser groupUser) {
		InputStream is = null;
		try {
			Socket socket = new Socket(ip, 9090);//10.188.199.3
			StringBuilder builder = new StringBuilder();
			builder.append("POST ");
			String str = "/plugins/kingrayplugin/userservice?actionType=delete&secret=jinruiyi"
					+ "&userName="
					+ groupUser.getUserName();
			builder.append(str);
			builder.append("\r\n");
			builder.append("Host: 10.188.199.3:9090 \r\n");
			builder.append("Connection: keep-alive  \r\n");
			builder.append("Cache-Control: max-age=0  \r\n");
			builder.append("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8  \r\n");
			builder.append("User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36  \r\n");
			builder.append("Accept-Encoding: gzip,deflate,sdch  \r\n");
			builder.append("Accept-Language: zh-CN,zh;q=0.8  \r\n\r\n");
			OutputStream os = socket.getOutputStream();
//			System.out.println(builder.toString());
			os.write(builder.toString().getBytes());
			os.flush();
			is = socket.getInputStream();
			
			String rs = null;
			StringBuilder stringBuilder = new StringBuilder();
			byte[] data = new byte[1024]; // 1k缓存
			int length = -1;
			while ((length = is.read(data)) > 0) {
				if(length != data.length){ // 读取的数据长度不是data的长度，那么就要读取有效的字节
					byte[] dataDes = new byte[length];
					System.arraycopy(data, 0, dataDes, 0, length); // 拷贝不是标准长度的字节
					data = dataDes;
				}
				stringBuilder.append(new String(data));
			}
			rs = stringBuilder.toString();
			System.out.println(rs);
			
//			BufferedReader br = new BufferedReader(new InputStreamReader(is));
//			StringBuilder sb = new StringBuilder();
//			while (br.read() != -1) {
//				sb.append(br.readLine());
//			}
//			String content = new String(sb);
//			content = new String(content.getBytes("UTF-8"), "ISO-8859-1");
//			System.out.println(content);
//			br.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(is != null){
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private static void sendUpdateRequestBySocket(GroupUser groupUser) {
		InputStream is = null;
		try {
			Socket socket = new Socket(ip, 9090);//10.188.199.3
			StringBuilder builder = new StringBuilder();
			builder.append("POST ");
			String str = "/plugins/kingrayplugin/userservice?actionType=update&secret=jinruiyi"
					+ "&userName="
					+ groupUser.getUserName()
					+ "&name="
					+ groupUser.getName()
					+ "&groups="
					+ groupUser.getGroupName()
					+ "&password="
					+ groupUser.getPassword()
					+ "&sortNumber="
					+ groupUser.getSortNumber();
			builder.append(str);
			builder.append("\r\n");
			builder.append("Host: 10.188.199.3:9090 \r\n");
			builder.append("Connection: keep-alive  \r\n");
			builder.append("Cache-Control: max-age=0  \r\n");
			builder.append("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8  \r\n");
			builder.append("User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36  \r\n");
			builder.append("Accept-Encoding: gzip,deflate,sdch  \r\n");
			builder.append("Accept-Language: zh-CN,zh;q=0.8  \r\n\r\n");
			OutputStream os = socket.getOutputStream();
//			System.out.println(builder.toString());
			os.write(builder.toString().getBytes());
			os.flush();
			is = socket.getInputStream();
			
			String rs = null;
			StringBuilder stringBuilder = new StringBuilder();
			byte[] data = new byte[1024]; // 1k缓存
			int length = -1;
			while ((length = is.read(data)) > 0) {
				if(length != data.length){ // 读取的数据长度不是data的长度，那么就要读取有效的字节
					byte[] dataDes = new byte[length];
					System.arraycopy(data, 0, dataDes, 0, length); // 拷贝不是标准长度的字节
					data = dataDes;
				}
				stringBuilder.append(new String(data));
			}
			rs = stringBuilder.toString();
			System.out.println(rs);
			
//			BufferedReader br = new BufferedReader(new InputStreamReader(is));
//			StringBuilder sb = new StringBuilder();
//			while (br.read() != -1) {
//				sb.append(br.readLine());
//			}
//			String content = new String(sb);
//			content = new String(content.getBytes("UTF-8"), "ISO-8859-1");
//			System.out.println(content);
//			br.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(is != null){
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	private static void sendRequestBySocket(GroupUser groupUser) {
		InputStream is = null;
		try {
			Socket socket = new Socket(ip, 9090);//10.188.199.3
			StringBuilder builder = new StringBuilder();
			builder.append("POST ");
			String str = "/plugins/kingrayplugin/userservice?actionType=add&secret=jinruiyi"
					+ "&userName="
					+ groupUser.getUserName()
					+ "&name="
					+ groupUser.getName()
					+ "&groups="
					+ groupUser.getGroupName()
					+ "&password="
					+ groupUser.getPassword()
					+ "&sortNumber="
					+ groupUser.getSortNumber();
			builder.append(str);
			builder.append("\r\n");
			builder.append("Host: 10.188.199.3:9090 \r\n");
			builder.append("Connection: keep-alive  \r\n");
			builder.append("Cache-Control: max-age=0  \r\n");
			builder.append("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8  \r\n");
			builder.append("User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36  \r\n");
			builder.append("Accept-Encoding: gzip,deflate,sdch  \r\n");
			builder.append("Accept-Language: zh-CN,zh;q=0.8  \r\n\r\n");
			OutputStream os = socket.getOutputStream();
//			System.out.println(builder.toString());
			os.write(builder.toString().getBytes());
			os.flush();
			is = socket.getInputStream();
			
			String rs = null;
			StringBuilder stringBuilder = new StringBuilder();
			byte[] data = new byte[1024]; // 1k缓存
			int length = -1;
			while ((length = is.read(data)) > 0) {
				if(length != data.length){ // 读取的数据长度不是data的长度，那么就要读取有效的字节
					byte[] dataDes = new byte[length];
					System.arraycopy(data, 0, dataDes, 0, length); // 拷贝不是标准长度的字节
					data = dataDes;
				}
				stringBuilder.append(new String(data));
			}
			rs = stringBuilder.toString();
			System.out.println(rs);
			
//			BufferedReader br = new BufferedReader(new InputStreamReader(is));
//			StringBuilder sb = new StringBuilder();
//			while (br.read() != -1) {
//				sb.append(br.readLine());
//			}
//			String content = new String(sb);
//			content = new String(content.getBytes("UTF-8"), "ISO-8859-1");
//			System.out.println(content);
//			br.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(is != null){
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private static void sendGroupRequestBySocket(Group group) {
		try {
			Socket socket = new Socket(ip, 9090);//10.188.199.3
			StringBuilder builder = new StringBuilder();
			builder.append("POST ");
			String str = "/plugins/kingrayplugin/userservice?actionType=updateGroupSortNumber&secret=jinruiyi"
					+ "&groupName="
					+ group.getGroupName()
					+ "&sortNumber="
					+ group.getSortNumber();
			builder.append(str);
			builder.append("\r\n");
			builder.append("Host: 10.188.199.3:9090 \r\n");
			builder.append("Connection: keep-alive  \r\n");
			builder.append("Cache-Control: max-age=0  \r\n");
			builder.append("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8  \r\n");
			builder.append("User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36  \r\n");
			builder.append("Accept-Encoding: gzip,deflate,sdch  \r\n");
			builder.append("Accept-Language: zh-CN,zh;q=0.8  \r\n\r\n");
			OutputStream os = socket.getOutputStream();
//			System.out.println(builder.toString());
			os.write(builder.toString().getBytes());
			os.flush();
			InputStream is = socket.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			StringBuilder sb = new StringBuilder();
			while (br.read() != -1) {
				sb.append(br.readLine());
			}
			String content = new String(sb);
//			content = new String(content.getBytes("UTF-8"), "ISO-8859-1");
			System.out.println(content);
			br.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

//	private static void sendRequest(GroupUser groupUser) {
//		try {
//			URL url = new URL(
//					"http://10.188.199.3:9090/plugins/kingrayplugin/userservice?actionType=add&secret=jinruiyi"
//							+ "&userName="
//							+ groupUser.getUserName()
//							+ "&name="
//							+ groupUser.getName()
//							+ "&groups="
//							+ groupUser.getGroupName()
//							+ "&password="
//							+ groupUser.getPassword());
//			HttpURLConnection urlConnection = (HttpURLConnection) url
//					.openConnection();
//			// http://10.188.199.3:9090/plugins/kingrayplugin/userservice?actionType=add&userName=%E9%99%88%E7%81%AB%E5%BC%BA&name=%E9%99%88%E7%81%AB%E5%BC%BA&groups=IT%E9%83%A8&secret=jinruiyi&password=chenhuoqiang88
//			urlConnection.setRequestMethod("GET");
//			urlConnection
//					.setRequestProperty(
//							"User-Agent",
//							"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");// ���ӱ�ͷ��ģ�����������ֹ����?
//			urlConnection.setRequestProperty("Accept", "text/html");// ֻ����text/html���ͣ���ȻҲ���Խ���ͼƬ,pdf,*/*���⣬����tomcat/conf/web���涨����Щ
//			//
//			// urlConnection.addRequestProperty("actionType", "add");
//			// urlConnection.addRequestProperty("secret", "jinruiyi");
//			// urlConnection.addRequestProperty("userName",
//			// groupUser.getUserName());
//			// urlConnection.addRequestProperty("name", groupUser.getName());
//			// urlConnection.addRequestProperty("groups",
//			// groupUser.getGroupName());
//			// urlConnection.addRequestProperty("password",
//			// groupUser.getPassword());
//			// urlConnection.setDoOutput(true);
//
//			// StringBuilder param = new StringBuilder();
//			// param.append("?actionType=add");
//			// param.append("&secret=jinruiyi");
//			// param.append("&userName=");
//			// param.append(groupUser.getUserName());
//			// param.append("&name=");
//			// param.append(groupUser.getName());
//			// param.append("&groups=");
//			// param.append(groupUser.getGroupName());
//			// param.append("&password=");
//			// param.append(groupUser.getPassword());
//
//			OutputStream os = urlConnection.getOutputStream();
//			os.write("".getBytes());
//
//			// System.out.println(urlConnection.toString());
//			os.flush();
//			os.close();
//
//			InputStream is = urlConnection.getInputStream();
//			BufferedReader br = new BufferedReader(new InputStreamReader(is));
//			StringBuilder sb = new StringBuilder();
//			while (br.read() != -1) {
//				sb.append(br.readLine());
//			}
//			String content = new String(sb);
//			content = new String(content.getBytes("UTF-8"), "ISO-8859-1");
//			System.out.println(content);
//			br.close();
//		} catch (MalformedURLException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}

	/**
	 * 
	 * <br>2013-7-18 上午9:53:57
	 * @return
	 */
	private static List<GroupUser> getGroupUsers() {
		Connection connection = DBConnectionCMS.getInstance().getConnection();
		PreparedStatement ps = null;
		String sql = "select g.departname, up.username, up.name, up.password, u.sort from newcms.kr_department g, newcms.kr_user u, newcms.kr_up up where g.id = u.departmentid  and u.status = 1 and u.tduser = up.username order by g.sort";// and u.status = 1  -----  and g.departname='�ʽ�'
		List<GroupUser> groupUsers = null;
		try {
			ps = connection.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			groupUsers = new ArrayList<GroupUser>();
			while (rs.next()) {
				String groupName = rs.getString(1);
				String userName = rs.getString(2);
				String name = rs.getString(3);
				String password = rs.getString(4);
				int sortNumber = rs.getInt(5);
				GroupUser groupUser = new GroupUser(groupName, userName, name,
						password, sortNumber);
				groupUsers.add(groupUser);
				System.out.println(groupUser);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return groupUsers;
	}
	
	
	/**
	 * 获取已经离职的用户
	 * <br>2013-7-18 上午9:53:57
	 * @return
	 */
	private static List<GroupUser> getDeletedGroupUsers() {
		Connection connection = DBConnectionCMS.getInstance().getConnection();
		PreparedStatement ps = null;
		String sql = "select g.departname, up.username, up.name, up.password, u.sort from newcms.kr_department g, newcms.kr_user u, newcms.kr_up up where g.id = u.departmentid  and u.status = 0 and u.tduser = up.username order by g.sort";// and u.status = 1  -----  and g.departname='�ʽ�'
		List<GroupUser> groupUsers = null;
		try {
			ps = connection.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			groupUsers = new ArrayList<GroupUser>();
			while (rs.next()) {
				String groupName = rs.getString(1);
				String userName = rs.getString(2);
				String name = rs.getString(3);
				String password = rs.getString(4);
				int sortNumber = rs.getInt(5);
				GroupUser groupUser = new GroupUser(groupName, userName, name,
						password, sortNumber);
				groupUsers.add(groupUser);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return groupUsers;
	}
	
	/**
	 * 
	 * <br>2013-7-18 上午9:53:36
	 * @return
	 */
	private static List getGroups() {
		Connection connection = DBConnectionCMS.getInstance().getConnection();
		PreparedStatement ps = null;
		String sql = "select departname, sort from newcms.kr_department";
		List<Group> groups = null;
		try {
			ps = connection.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			groups = new ArrayList<Group>();
			while (rs.next()) {
				String groupName = rs.getString(1);
				int sortNumber = rs.getInt(2);
				Group group = new Group(groupName, sortNumber);
				groups.add(group);
				System.out.println(group);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return groups;
	}
	

}

class Group{
	private String groupName;
	private int sortNumber;
	public Group(String groupName, int sortNumber){
		this.groupName = groupName;
		this.sortNumber = sortNumber;
	}
	public String getGroupName() {
		try {
			return URLEncoder.encode(new String(groupName), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return groupName;
	}
	public void setGroupName(String groupName) {
		this.groupName = groupName;
	}
	public int getSortNumber() {
		return sortNumber;
	}
	public void setSortNumber(int sortNumber) {
		this.sortNumber = sortNumber;
	}
	@Override
	public String toString() {
		return "groupName: " + groupName + ", sortNumber: " + sortNumber;
	}
}
